package free.akerigan.yafb2lib.library;

import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Iterator;

import de.schlichtherle.util.zip.ZipEntry;
import de.schlichtherle.util.zip.ZipFile;

import free.akerigan.yafb2lib.book.FB2Parser;

public class LibraryModelFactory {

    public static LibraryModel createFromFilesystem(String path) {
	LibraryModel library = new LibraryModel();
	String[] paths = path.split(";");
	for (int i = 0; i < paths.length; i++) {
	    File dir = new File(paths[i].trim());
	    File[] files = dir.listFiles(new FilenameFilter() {

		public boolean accept(File dir, String name) {
		    if (name.endsWith(".zip")) {
			return true;
		    } else {
			return false;
		    }
		}

	    });
	    for (int j = 0; j < files.length; j++) {
		System.out.println(files[j]);
		try {
		    ZipFile zipFile = new ZipFile(files[j], "windows-1251");
		    Enumeration<ZipEntry> entries = zipFile.entries();
		    while (entries.hasMoreElements()) {
			ZipEntry entry = entries.nextElement();
			if (entry.getName().toLowerCase().endsWith(".fb2")) {
			    FB2Parser.parse(zipFile.getInputStream(entry),
				    library);
			}
		    }
		} catch (IOException e) {
		    e.printStackTrace();
		}
	    }

	}
	return library;
    }
}
